//
//  ViewController.m
//  9-4
//
//  Created by Macmini on 17/9/4.
//  Copyright © 2017年 Macmini. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    UITableView *tableView;
    NSMutableArray *tels;
    NSArray *backup;
 
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    tels = [NSMutableArray new];
    [tels addObject:@"吴奇隆,110"];
    [tels addObject:@"李科宪,120"];
    [tels addObject:@"黄辉,10010"];
    [tels addObject:@"宋怡林,10086"];
    [tels addObject:@"罗佳明,114"];
    backup = tels.copy;
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    [self.view addSubview:tableView];
    
    UISearchBar *bar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    bar.delegate = self;
    self.navigationItem.titleView = bar;

}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"%@",searchText);
    if (searchText.length == 0) {
        tels = backup.mutableCopy;
        return;
    }
    NSMutableArray *res = [NSMutableArray new];
    for (NSString *tel in backup) {
        if ([tel containsString:searchText]) {
            [res addObject:tel];
        }
    }
    tels = res;
    [tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return tels.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView_ cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView_ dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    NSString *tel = tels[indexPath.row];
    NSArray *tmp = [tel componentsSeparatedByString:@","];
    cell.textLabel.text = tmp.firstObject;
    cell.detailTextLabel.text = tmp.lastObject;
    return cell;
}


//-(NSInteger)tableView:(UITableView *)
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *tel = tels[indexPath.row];
    NSArray *tmp = [tel componentsSeparatedByString:@","];
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",tmp.lastObject]]];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}















@end
